package gripper.ftp.handle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import gripper.ftp.FtpSession;
import gripper.ftp.PathConvert;

public class RNTOHandle implements Handle {
	FtpSession ftpSession;
	public RNTOHandle(FtpSession ftpSession) {
		this.ftpSession = ftpSession;
	}
	public void process(String line, BufferedReader br, OutputStream os) throws IOException {
		final String[] splited = line.split(" ");
		String fileName = splited[1].trim();
		fileName = ftpSession.currentDir + "/" + fileName;
		fileName = PathConvert.toServerPath(ftpSession.getRootDir(), fileName);
		if(ftpSession.fileNameRNFR==null){
			os.write("550 Requested action not taken.\r\n".getBytes());
			os.flush();
			return;
		}
		Path fromFile=Paths.get(ftpSession.fileNameRNFR);
		Path toFile=Paths.get(fileName);
		Files.move(fromFile, toFile);
		ftpSession.fileNameRNFR=null;
		os.write("250 Requested file action okay, completed.\r\n".getBytes());
		os.flush();
	}
}
